package com.tian.scroll.view_move.fragment.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.button.MaterialButton;

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2021/1/19 10:40
 */
public class ScrollMaterialButton extends MaterialButton {

    private final String TAG = "ScrollMaterialButton";

    private boolean scrollBy = true;

    private int preX, preY;

    public ScrollMaterialButton(@NonNull Context context) {
        super(context);
    }

    public ScrollMaterialButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollMaterialButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public boolean isScrollBy() {
        return scrollBy;
    }

    public void setScrollBy(boolean scrollBy) {
        this.scrollBy = scrollBy;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (scrollBy) {
            handleScrollBy(event);
        }
        return scrollBy;
    }





    private void handleScrollBy(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                preX = (int) event.getRawX();
                preY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int y = (int) event.getRawY();
                int x = (int) event.getRawX();
                int dy = y - preY;
                int dx = x - preX;
                scrollBy(-dx, -dy);
                preY = y;
                preX = x;
                break;
            default:
                break;
        }
    }

}
